import type { ResponseBody } from "@/api/typing";
import type { Options, State } from "./typing";
import { reactive } from "vue";

export const useFetchList = <T extends ResponseBody<any>>(
  queryList: (...args: any[]) => Promise<T>,
  options: Options<T["result"]> = {}
) => {
  const { autoFetch = true, params, coverData, onLoad } = options;
  const state = reactive<State<T["result"]>>({
    loading: false,
    list: [],
  });
  const reload = async () => {
    state.loading = true;
    const { success, result } = await queryList(params);
    state.loading = false;
    if (success) {
      if (coverData) {
        state.list = coverData(result);
      } else {
        state.list = result;
      }
      onLoad?.(state.list);
    }
  };
  if (autoFetch) reload();
  return { state, reload };
};
